//
//  QHHCPDownLoader.m
//  QHealthForDoctor
//
//  Created by 李志良的mac mini on 2020/4/14.
//  Copyright © 2020 李 志良. All rights reserved.
//热更新下载

#import "QHHCPDownLoader.h"
#import "NetReachablity.h"


@interface QHHCPDownLoader ()<NSURLSessionDelegate>

@property (nonatomic,strong) NSString *tempLocalFilePath;

@property (nonatomic,strong) NSString *ossurl;

@property (nonatomic,strong) NSURLSession *session;

@end

@implementation QHHCPDownLoader

-(id)initWithHCPWWWFolderName:(NSString*)wwwFolderName Success:(QHHCPDownLoaderDownLoadCompleteBlock)success Failed:(QHHCPDownLoaderDownLoadFailedBlock)failed{
    self = [super init];
    if(self){
        self.wwwFolderName = wwwFolderName;
        self.downloadCompleteBlock = success;
        self.downloadFaildBlock = failed;
    }
    return self;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];;
}

-(void)downLoadUpdateFilesWithDiffArray:(NSArray*)diffArray{
    _downLoadedFileCount = 0;
    _updateFilesArray = diffArray;
    
    //开始下载
    NSDictionary * downLoadFileDic = diffArray[_downLoadedFileCount];
    _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    [self startDownLoadfileWithFileInfo:downLoadFileDic];
}

-(void)startDownLoadfileWithFileInfo:(NSDictionary *)dataInfo
{
    _tempLocalFilePath = dataInfo[@"file"];
    _ossurl = dataInfo[@"ossurl"];
    NSURL * downloadUrl = nil;
    if ([self checkIsChinese:_ossurl])
    {
        downloadUrl = [NSURL URLWithString:[_ossurl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
    }
    else
    {
        downloadUrl = [NSURL URLWithString:_ossurl];
    }
    __weak typeof(self) ws = self;
    NSURLSessionDataTask *dataTask = [_session dataTaskWithURL:downloadUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error)
        {
            NSDictionary *downloadFileDic = ws.updateFilesArray[ws.downLoadedFileCount];
            NSString *serverDataMD5 = downloadFileDic[@"hash"];
            NSString *downloadDataMD5 = [data md5Hash];
            if ([serverDataMD5 isEqualToString:downloadDataMD5])
            {
                // 文件下载成功
                NSString *filePath = [ws createDirectoryWithUrl:[NSURL URLWithString:downloadFileDic[@"ossurl"]]];
                // 将文件转移到安全的地方去
                NSError *error;
                [data writeToFile:filePath options:NSDataWritingWithoutOverwriting error:&error];
                if (!error)
                {
                    [ws fileDownloadSuccess];
                }
                else
                {
//                    NSString *errMsg = [NSString stringWithFormat:@"文件写入失败:%@",error];
//                    DeBugLog(@"%@",errMsg);
//                    if (ws.downloadFaildBlock) {
//                        ws.downloadFaildBlock(errMsg);
//                    }
                }
            }
            else
            {
                NSString *errMsg = [NSString stringWithFormat:@"文件下载错误:%@",downloadFileDic[@"file"]];
                DeBugLog(@"%@",errMsg);
                if (ws.downloadFaildBlock) {
                    ws.downloadFaildBlock(errMsg);
                }
            }
        }
        else
        {
            NSString *errMsg = [NSString stringWithFormat:@"文件下载失败:%@",error.userInfo[@"NSLocalizedDescription"]];
            DeBugLog(@"%@",errMsg);
            if (ws.downloadFaildBlock) {
                ws.downloadFaildBlock(errMsg);
            }
        }
    }];

    [dataTask resume];
}

-(void)fileDownloadSuccess
{
    self.downLoadedFileCount++;
    if (self.downloadProgressBlock) {
        self.downloadProgressBlock(_downLoadedFileCount);
    }
    if (self.downLoadedFileCount == _updateFilesArray.count) {
        DeBugLog(@"下载完毕");
        if (self.downloadCompleteBlock) {
            self.downloadCompleteBlock();
        }
        return;
    }
    NSDictionary *downloadFileDic = _updateFilesArray[_downLoadedFileCount];
    [self startDownLoadfileWithFileInfo:downloadFileDic];
}

#pragma mark NSURLSessionDownloadDelegate

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    //下载进度
    DeBugLog(@"----%f", 1.0 * totalBytesWritten/totalBytesExpectedToWrite);
}

//-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
//{//下载完成调用
//    NSData *downloadData = [NSData dataWithContentsOfURL:location];
//    NSDictionary *downLoadFileDic = _updateFilesArray[self.downLoadedFileCount];
//    NSString *serverHashCode = downLoadFileDic[@"hash"];
//    NSString *downloadDataHashCode = [downloadData md5];
//    if ([serverHashCode isEqualToString:downloadDataHashCode])
//    {
//        // 下载成功
//        NSString *filePath = [self createDirectoryWithUrl:[NSURL URLWithString:_ossurl]];
//        //将文件转移到安全的地方去
//        NSError *error;
//        [[NSFileManager defaultManager]moveItemAtURL:location toURL:[NSURL fileURLWithPath:filePath] error:&error];
//        if (error) {
//            NSString *errMsg = [NSString stringWithFormat:@"文件移动失败:%@",error];
//            DeBugLog(@"%@",errMsg);
//            self.downloadFaildBlock(errMsg);
//        }
//        else
//        {
//            [self fileDownloadSuccess];
//        }
//    }
//    else
//    {
//         //文件下载错误。
//        NSString *errMsg = [NSString stringWithFormat:@"文件下载错误:%@",downLoadFileDic[@"file"]];
//        DeBugLog(@"%@",errMsg);
//        self.downloadFaildBlock(errMsg);
//    }
//}

//-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
//{//整个请求完成或者请求失败调用
//    if (error) {
//        DeBugLog(@"didCompleteWithError: %@",error);
//        self.downloadFaildBlock(error.domain);
//    }
//}

#pragma Private Method
-(NSString *)createDirectoryWithUrl:(NSURL *)url{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [self getFilePathWithURL:[url description]];
    
    NSRange range = [filePath rangeOfString:@"/" options:NSBackwardsSearch];
    NSString *folderPath = [filePath substringToIndex:range.location];
    BOOL fileExists = [fileManager fileExistsAtPath:folderPath];
    if (!fileExists) {
        [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
   return filePath;
}

-(NSString *)getFilePathWithURL:(NSString *)fileURL{
    NSArray *array = [fileURL componentsSeparatedByString:@"//"];
    return [self getCacheFilePath:[array lastObject]];
}

-(NSString *)getCacheFilePath:(NSString *)fileName{
    fileName = [NSString stringWithFormat:@"BufferedFile/%@",fileName];
    NSString *changeFileName = fileName;
    if (_tempLocalFilePath) {
        NSString *h5FilePrifix = [fileName componentsSeparatedByString:@"www"][0];
        NSString *h5FileString = [_tempLocalFilePath stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
        changeFileName = [NSString stringWithFormat:@"%@%@",h5FilePrifix,h5FileString];
    }
    NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [documentDir stringByAppendingPathComponent:changeFileName];
    return filePath;
}





//#pragma mark - AsyncFileDelegate
//- (void)asyncBufferSuccess:(AsyncFileBuffer *)buffer fileLocationPath:(NSString *)locPath {
//    //locPath 下载的文件在本地的路径
//    if ([[NSFileManager defaultManager]fileExistsAtPath:locPath]) {
//        NSData *fileData = [NSData dataWithContentsOfFile:locPath];
//        if (fileData.length > 0)
//        {
//            NSString *newHashData = [fileData md5];
//            DeBugLog(@"locPath:%@",newHashData);
//            // 防止 downLoadedFileCount 大于数据元素个数 ，导致的越界。
//            if (self.downLoadedFileCount >= _updateFilesArray.count) {
//                self.downLoadedFileCount = _updateFilesArray.count -1;
//            }
//            NSDictionary * downLoadFileDic =  _updateFilesArray[self.downLoadedFileCount];
//            NSString *oldHashData = downLoadFileDic[@"hash"];
//            if ([newHashData isEqualToString:oldHashData])
//            {
//                [self fileDownSuccess];
//            }
//            else
//            {
//                if (self.downloadFaildBlock) {
//                    NSString *errMsg = [NSString stringWithFormat:@"文件下载错误:%@",downLoadFileDic[@"file"]];
//                    DeBugLog(@"locPath:%@,\n oldHashData:%@,\n newHashData:%@",downLoadFileDic[@"file"],oldHashData,newHashData);
//                    self.downloadFaildBlock(errMsg);
//                }
//            }
//        }
//        else
//        {
//            if (self.downloadFaildBlock) {
//                self.downloadFaildBlock(@"文件下载错误:文件长度为0");
//            }
//        }
//    }
//    else
//    {
//        if (self.downloadFaildBlock) {
//            self.downloadFaildBlock(@"文件下载错误:文件不存在");
//        }
//    }
//}
//
//-(void)fileDownSuccess{
//    self.downLoadedFileCount++;
//    if(self.downloadProgressBlock){
//        self.downloadProgressBlock(self.downLoadedFileCount);
//       //    DeBugLog(@">>>>>>>>>>>>>>%f",(float)self.downLoadedFileCount/(float)_updateFilesArray.count);
//    }
//    if(self.downLoadedFileCount==_updateFilesArray.count){
//        //全部成功下载
//        DeBugLog(@"下载完毕");
//        if(self.downloadCompleteBlock){
//            self.downloadCompleteBlock();
//        }
//        return;
//    }
//    NSDictionary * downLoadFileDic = _updateFilesArray[self.downLoadedFileCount];
////    _asyncBuffer.H5FileName = downLoadFileDic[@"file"];
//
//    if ([self checkIsChinese:downLoadFileDic[@"file"]]) {
////        [_asyncBuffer loadFileFromURLString:[downLoadFileDic[@"ossurl"] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
//    }else{
////        [_asyncBuffer loadFileFromURLString:downLoadFileDic[@"ossurl"]];
//    }
//}


//- (void)asyncBuffer:(AsyncFileBuffer *)buffer progress:(float)progress fileSize:(uint)fileSize rate:(NSString *)rate {
    //下载进度：如果已下载到本地 该方法不会被调用
//   NSString *downSize = [buffer formatFileSize:fileSize*progress];
//    DeBugLog(@"已下载：%@  文件大小：%@",downSize,[buffer formatFileSize:fileSize]);
//    DeBugLog(@"进度：%.2f%%  下载速度：%@",progress*100,rate);
//    [self.fileLenthLabel setText:[buffer formatFileSize:fileSize]];
//
//    if (!_isBeginDownLoad) {
//        [self hideLoadingView];
//        [self showSubViews:YES];
//    }
//
//    _isBeginDownLoad = YES;
//
//    if (!isnan(progress)) {
//        _progressView.newprogress = progress;
//    }
//
//    [self.percentLabel setText:[NSString stringWithFormat:@"下载中...（%@/%@)",downSize,[buffer formatFileSize:fileSize]]];
//    if (progress*100 == 1) {
//        //        [self performSelector:@selector(leftButtonItemTapped) withObject:nil afterDelay:0.25];
//        [self leftButtonItemTapped];
//    }
//}

//- (void)asyncBufferFailed:(AsyncFileBuffer *)buffer {
//    DeBugLog(@"error : %@",buffer.error);
//
//    if (self.downloadFaildBlock) {
//        self.downloadFaildBlock(buffer.error.userInfo[@"NSLocalizedDescription"]);
//    }
//}

/**
 *  @author zhengju, 16-06-29 10:06:05
 *
 *  @brief 检测字符串中是否含有中文，备注：中文代码范围0x4E00~0x9FA5，
 *
 *  @param string 传入检测到中文字符串
 *
 *  @return 是否含有中文，YES：有中文；NO：没有中文
 */
- (BOOL)checkIsChinese:(NSString *)string{
    for (int i=0; i<string.length; i++) {
        unichar ch = [string characterAtIndex:i];
        if (0x4E00 <= ch  && ch <= 0x9FA5) {
            return YES;
        }
    }
    return NO;
}
@end
